# -*- coding: utf-8 -*-
# @Time    : 2020/11/24 14:56
# @Author  : suhong
# @File    : mg_err_2_wechat.py
# @Software: PyCharm
import json
import time
import pymysql
import requests
from re_common.baselibrary.utils.basepymongo import BasePyMongo

from re_common.baselibrary.utils.basetime import BaseTime


class SendErr2Wechat(object):
    def __init__(self):
        self.start_time = time.time()
        self.basemongo = BasePyMongo(
            "mongodb://192.168.31.30:32417/htmljson.err_msg?authSource=htmljson")
        self.basemongo.use_db("htmljson")
        self.basemongo.create_col("err_msg")
        self.bt = BaseTime()

        self.home = 'http://127.0.0.1:8000'
        self.url = self.home + "/globalapi/wechat_router/wechat/send_msg"

    def check_time(self,c_time,hours=2):
        """
        检查c_time是否和上次相差hour个小时
        :param c_time:输入时间
        :param hours:相差的小时数
        :return:
        """
        if c_time - self.start_time >= hours * 3600:
            self.start_time = c_time
            return True
        else:
            return False

    def get_username(self,task_name):
        """
        :param task_name: 或者task_name 属于的 who
        :return:
        """
        conn = pymysql.connect("192.168.31.209", "root", "vipdatacenter", "data_gather_record", charset="utf8mb4")
        cur = conn.cursor()
        sql = "select who from task where provider = '{}'".format(task_name)
        cur.execute(sql)
        result = cur.fetchone()
        if result is None:
            # 通知所有人
            author = "所有人"
        else:
            author = result[0].split(";")[1]
        return author


    def read_mg_err(self,g_time=2):
        """
        :param g_time: 获取几个小时前的数据
        :return:
        """
        query_time = self.bt.get_hours_before(self.bt.get_now_datetime(), g_time)

        myquery = {"write_time": {"$gte": query_time}}
        r = self.basemongo.find(myquery)
        for xx in r:
            task_name = xx['task_name']
            author = self.get_username(task_name)

            self.send_msg_2_wechat(author,xx)


    def send_msg_2_wechat(self,author,info):
        """
        发送到企业微信
        :param author: 发送对象
        :param info: 发送消息
        :return:
        """
        msg = ""
        for k,v in info.items():
            msg += str(k) + ":" + str(v) + "\n"
        data = {
            "proxy": "",
            "input_code": "",
            "input_msg": "",
            "data": {
                "author": author,
                "msg": str(msg)
            }
        }
        r = requests.post(self.url,data=json.dumps(data))
        print("发送消息成功")


    def run(self):

        while True:
            c_time = time.time()
            if self.check_time(c_time,hours=2):
                self.read_mg_err(g_time=2)
            else:
                print("等待")
                # time.sleep(2)
                time.sleep(15*60)





        


if __name__ == '__main__':
    m = SendErr2Wechat()
    m.run()
